import Taro from "@tarojs/taro";
import { createAlova } from "alova";
import { Subject, lastValueFrom } from "rxjs";
export const alovaInstance = createAlova<any, any, any, any, any>({
  // baseURL: `http://192.168.202.135:3000`,
  // baseURL: "http://192.168.201.56:3000",
  // baseURL: "http://localhost:3001",
  // baseURL: "https://convert.vmic.top",
  // baseURL: "http://106.52.44.176",
  baseURL: "http://localhost:27082",

  timeout: 30000,
  // cacheLogger: false,
  localCache: {
    GET: 0,
    POST: 0
  },
  beforeRequest(method) {
    method.config.headers = {
      Authorization: "Bearer " + alovaInstance.storage.get("access_token")
    };
  },
  storageAdapter: {
    set(key, value) {
      Taro.setStorageSync(key, value);
    },
    get(key) {
      return Taro.getStorageSync(key);
    },
    remove(key) {
      Taro.removeStorageSync(key);
    }
  },

  requestAdapter: function (request, method) {
    const config = method.config;
    const uploadData = config.meta?.uploadData;
    const headers = new Subject();
    const response = new Subject<TaroGeneral.IAnyObject>();

    const abort = new Subject();

    let requestPromise:
      | ReturnType<typeof Taro.uploadFile>
      | ReturnType<typeof Taro.request>;
    if (uploadData) {
      // 适配上传
      requestPromise = Taro.uploadFile({
        url: request.url,
        ...uploadData,
        formData: request.data,
        header: Object.assign(config.headers, request.headers)
      });
    } else {
      requestPromise = Taro.request({
        url: request.url,
        method: request.type,
        header: Object.assign(config.headers, request.headers),
        data: request.data,
        timeout: method.config.timeout
      });
    }

    requestPromise
      .then((res) => {
        if (![200, 201].includes(res.statusCode)) {
          response.error(res.errorMsg);
        }
        const data = uploadData ? JSON.parse(res.data) : res.data;
        response.next(data);
        response.complete();
        headers.next(res.header);
        headers.complete();
      })
      .catch((error) => {
        Taro.showToast({
          icon: "error",
          title: "服务器异常~"
        });
        response.error(error);
      });

    return {
      response: () => lastValueFrom(response),
      headers: () => lastValueFrom(headers),
      onDownload: () => Promise.resolve(),
      onUpload: () => Promise.resolve(),
      abort: () => lastValueFrom(abort)
    };
  }
});
